package com.taptech.doufu.services.offline;

import java.io.File;
import java.io.IOException;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.db.offline.OffLineDataBaseUtil;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;

public class OffLineDownLoader {

	private Context context;
	private OffLineDownRunnable downRunnable;
	private OffLineInfoBean offLineInfoBean;
	private int downloadLength;
	private OffLineDataBaseUtil offLineDataBaseUtil;
	
	public OffLineDownLoader(Context context,OffLineInfoBean bean) {
		this.context = context;
		this.offLineInfoBean = bean;
		offLineDataBaseUtil = new OffLineDataBaseUtil(context);
	}
	
	public void download(Handler handler){
		File file = new File(Constant.AppDir.DIR_OFFLINE_DATA+
				offLineInfoBean.getOffline_url().substring(offLineInfoBean.getOffline_url().lastIndexOf("/")+1));
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		downRunnable = new OffLineDownRunnable(handler,context, this, offLineInfoBean, file);
		OffLineService.downExecutor.execute(downRunnable);
	}
	
	/**
	 * 当前下载大小
	 * @param size
	 */
	protected synchronized void append(int size){  //多线程访问需加锁
		downloadLength += size;
		if (downloadLength == offLineInfoBean.getOffline_filemax()) {
			offLineInfoBean.setOffline_status(Constant.OffLineSTATUS.DOWN_SUCCESS);
			offLineInfoBean.setOffline_fileload(offLineInfoBean.getOffline_filemax());
			//更新下载状态
			offLineDataBaseUtil.update(offLineInfoBean.getOffline_novelid(), Constant.OffLineSTATUS.DOWN_SUCCESS);
		}else {
			offLineInfoBean.setOffline_status(Constant.OffLineSTATUS.DOWN_ING);
			offLineInfoBean.setOffline_fileload(downloadLength);
			//更新下载状态
			offLineDataBaseUtil.update(offLineInfoBean.getOffline_novelid(), Constant.OffLineSTATUS.DOWN_ING);
		}
		Intent receive = new Intent();
		receive.putExtra("offline_receive", offLineInfoBean);
		receive.setAction("doufu.offline.novel.load");
		context.sendBroadcast(receive);
	}
	
}
